<template>
  <div class="activity-list-page">
    <div class="page-container">
      <h1 class="page-title">活动列表</h1>
      
      <!-- 筛选条件 -->
      <div class="filter-section card">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="分类">
            <el-select v-model="filterForm.categoryId" placeholder="选择分类" clearable>
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="filterForm.status" placeholder="活动状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="即将开始" value="upcoming" />
              <el-option label="进行中" value="ongoing" />
              <el-option label="已结束" value="ended" />
            </el-select>
          </el-form-item>
          <el-form-item label="搜索">
            <el-input
              v-model="filterForm.keyword"
              placeholder="搜索活动名称或描述"
              prefix-icon="el-icon-search"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 活动列表 -->
      <div class="activity-grid">
        <div
          v-for="activity in activities"
          :key="activity.id"
          class="activity-card"
          @click="goToDetail(activity.id)"
        >
          <!-- 活动图片 -->
          <div class="card-image">
            <img :src="activity.coverImage || '/default-activity.jpg'" alt="活动封面" />
            <div v-if="activity.isHot" class="hot-badge">热门</div>
          </div>

          <!-- 活动信息 -->
          <div class="card-content">
            <h3 class="activity-title">{{ activity.title }}</h3>
            <div class="activity-meta">
              <span class="meta-item">
                <i class="el-icon-time"></i>
                {{ formatDate(activity.startTime) }}
              </span>
              <span class="meta-item">
                <i class="el-icon-location"></i>
                {{ activity.location }}
              </span>
              <span class="meta-item">
                <i class="el-icon-user"></i>
                {{ activity.participantCount || 0 }}人已报名
              </span>
            </div>
            <p class="activity-desc">{{ truncateText(activity.description, 80) }}</p>
            <div class="card-footer">
              <span class="activity-category">{{ getCategoryName(activity.categoryId) }}</span>
              <span v-if="getMappedStatus(activity.status) === 'ENDED'" class="status-badge ended">已结束</span>
              <span v-else-if="getMappedStatus(activity.status) === 'ONGOING'" class="status-badge ongoing">进行中</span>
              <span v-else class="status-badge upcoming">即将开始</span>
            </div>
          </div>
        </div>
        <div v-if="loading" class="loading-state">
          <el-skeleton :rows="6" animated />
        </div>
        <div v-else-if="activities.length === 0" class="empty-state">
          <el-empty description="暂无符合条件的活动" />
        </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="pageParams.total > 0" class="pagination">
        <el-pagination
          v-model:current-page="pageParams.pageNum"
          v-model:page-size="pageParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { formatDate, truncateText, mapStatusToFrontend } from '../utils/common'
import { getActivityList } from '../api/activity'
import { getAllCategories } from '../api/category'

export default {
  name: 'ActivityList',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const loading = ref(false)
    
    // 数据存储
    const activities = ref([])
    const categories = ref([])
    
    // 筛选表单
    const filterForm = ref({
      categoryId: '',
      status: '',
      keyword: ''
    })
    
    // 分页参数
    const pageParams = ref({
      pageNum: 1,
      pageSize: 20,
      total: 0
    })
    
    // 获取分类列表
    const fetchCategories = async () => {
      try {
        const response = await getAllCategories()
        categories.value = response || []
      } catch (error) {
        ElMessage.error('获取分类失败')
        console.error('获取分类列表失败:', error)
      }
    }
    
    // 获取活动列表
    const fetchActivities = async () => {
      try {
        loading.value = true
        const params = {
          page: pageParams.value.pageNum,
          pageSize: pageParams.value.pageSize,
          ...filterForm.value
        }
        
        const response = await getActivityList(params)
        console.log(response)
        activities.value = response.data || []
        pageParams.value.total = response.total || 0
      } catch (error) {
        ElMessage.error('获取活动列表失败')
        console.error('获取活动列表失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      pageParams.value.pageNum = 1
      fetchActivities()
    }
    
    // 重置筛选
    const resetFilter = () => {
      filterForm.value = {
        categoryId: '',
        status: '',
        keyword: ''
      }
      pageParams.value.pageNum = 1
      fetchActivities()
    }
    
    // 跳转到活动详情
    const goToDetail = (activityId) => {
      router.push(`/activity/${activityId}`)
    }
    
    // 获取分类名称
    const getCategoryName = (categoryId) => {
      if (!Array.isArray(categories.value)) {
        console.warn('categories is not an array:', categories.value)
        return '未分类'
      }
      const category = categories.value.find(c => c && c.id === categoryId)
      return category ? category.name : '未分类'
    }
    
    // 处理分页大小变化
    const handleSizeChange = (size) => {
      pageParams.value.pageSize = size
      fetchActivities()
    }
    
    // 处理当前页变化
    const handleCurrentChange = (current) => {
      pageParams.value.pageNum = current
      fetchActivities()
    }
    
    // 监听路由参数变化
    watch(() => route.query, (newQuery) => {
      if (newQuery.category) {
        filterForm.value.categoryId = newQuery.category
      }
      if (newQuery.status) {
        filterForm.value.status = newQuery.status
      }
      if (newQuery.keyword) {
        filterForm.value.keyword = newQuery.keyword
      }
      fetchActivities()
    }, { immediate: true })
    
    // 获取映射后的状态
    const getMappedStatus = (status) => {
      return mapStatusToFrontend(status)
    }
    
    onMounted(() => {
      fetchCategories()
    })
    
    return {
      activities,
      categories,
      loading,
      filterForm,
      pageParams,
      handleSearch,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      goToDetail,
      getCategoryName,
      getMappedStatus,
      formatDate,
      truncateText
    }
  }
}
</script>

<style scoped>
.activity-list-page {
  min-height: calc(100vh - 180px);
}

.filter-section {
  margin-bottom: 24px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: end;
  gap: 16px;
}

.filter-form .el-form-item {
  margin-bottom: 16px;
}

.activity-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 30px;
}

.loading-state {
  grid-column: 1 / -1;
}

.empty-state {
  grid-column: 1 / -1;
  padding: 60px 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

@media (max-width: 768px) {
  .filter-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-form .el-form-item {
    width: 100%;
  }
  
  .activity-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }
}

/* 添加活动卡片样式 */
.activity-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
}

.activity-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.card-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.activity-card:hover .card-image img {
  transform: scale(1.05);
}

.hot-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #ff4d4f;
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.card-content {
  padding: 16px;
}

.activity-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.activity-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.activity-desc {
  font-size: 14px;
  color: #909399;
  line-height: 1.5;
  margin-bottom: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.activity-category {
  background-color: #f5f7fa;
  color: #606266;
  padding: 2px 8px;
  border-radius: 4px;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: 500;
}

.status-badge.upcoming {
  background-color: #ecf5ff;
  color: #409eff;
}

.status-badge.ongoing {
  background-color: #f0f9eb;
  color: #67c23a;
}

.status-badge.ended {
  background-color: #f5f7fa;
  color: #909399;
}
</style>